<template>
  <view class="login-container">
    <view class="login-form">
      <!-- 标志和标题 -->
      <view class="logo-container">
        <h2>温室卷帘门控制系统</h2>
      </view>
      <view class="logo-container">
        <image src="/static/logo.png" class="login-logo" mode="aspectFit" />
      </view>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-tip">
        <text>正在注册...</text>
      </view>

      <!-- 输入框组 -->
      <view class="input-group">
        <text class="label">用户名</text>
        <view class="input-field">
          <input 
            type="text" 
            placeholder="请输入用户名" 
            v-model="username" 
            :class="{ 'input-error': error && !username }"
          />
        </view>
      </view>

      <view class="input-group">
        <text class="label">密码</text>
        <view class="input-field">
          <input 
            type="password" 
            placeholder="请输入密码" 
            v-model="password" 
            :class="{ 'input-error': error && !password }"
          />
        </view>
      </view>

      <view class="input-group">
        <text class="label">确认密码</text>
        <view class="input-field">
          <input 
            type="password" 
            placeholder="请再次输入密码" 
            v-model="confirmPassword" 
            :class="{ 'input-error': error && !confirmPassword }"
          />
        </view>
      </view>

      <!-- 错误提示 -->
      <view v-if="error" class="error-tip">
        <text>{{ errorMsg }}</text>
      </view>

      <!-- 注册按钮 -->
      <button 
        class="login-button" 
        @click="handleRegister" 
        :disabled="loading"
      >
        {{ loading ? '注册中...' : '立即注册' }}
      </button>

      <!-- 跳转登录 -->
      <view class="register-link">
        <text class="link-text" @click="goToLogin">已有账号？登录</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      username: "",
      password: "",
      confirmPassword: "",
      loading: false,
      error: false,
      errorMsg: "",
      apiUrl: "http://192.168.32.38" // 统一API地址（需与后端一致）
    };
  },

  methods: {
    // 注册主逻辑
    async handleRegister() {
      console.log('开始注册流程');
      // 输入验证
      this.validateInput();
      if (this.error) return;

      try {
        this.loading = true;
        this.error = false;

        const res = await uni.request({
          url: `${this.apiUrl}/list/add`, // 对应list.js的/add接口
          method: "POST",
          data: {
            username: this.username,
            password: this.password 
          },
          timeout: 8000 // 超时时间
        });

        console.log('服务器响应:', res);

        // 处理响应
        if (res.statusCode !== 200) {
          throw new Error(`服务器状态码错误：${res.statusCode}`);
        }

        if (res.data.status === 200) {
          this.handleSuccess();
        } else {
          console.log('服务器返回错误数据:', res.data);
          throw new Error(res.data.message || "注册失败，请重试");
        }

      } catch (error) {
        // 统一错误处理
        this.handleError(error);
      } finally {
        this.loading = false;
      }
    },

    // 输入验证
    validateInput() {
      if (!this.username.trim()) {
        this.showError("用户名不能为空");
        return false;
      }
      if (!this.password.trim()) {
        this.showError("密码不能为空");
        return false;
      }
      if (this.password !== this.confirmPassword) {
        this.showError("两次输入的密码不一致");
        return false;
      }
      if (this.password.length < 6) {
        this.showError("密码长度至少6位");
        return false;
      }
      this.error = false;
      return true;
    },

    // 注册成功处理
    handleSuccess() {
      uni.showToast({
        title: "注册成功",
        icon: "none",
        duration: 1500,
        success: () => {
          uni.navigateTo({ url: "/pages/login/login" }); // 跳转登录页
        }
      });
    },

    // 错误处理
    handleError(error) {
      console.error("注册错误:", error); // 关键：查看控制台日志定位问题

      // 区分错误类型
      if (error.message.includes("timeout")) {
        this.showError("请求超时，请检查网络连接");
      } else if (error.message.includes("connect")) {
        this.showError("无法连接到服务器，请检查IP/端口");
      } else if (error.message.includes("statusCode")) {
        this.showError("服务器内部错误，请联系管理员");
      } else {
        this.showError(error.message || "注册失败，请稍后重试");
      }
    },

    // 跳转登录页
    goToLogin() {
      uni.navigateTo({ url: "/pages/login/login" });
    },

    // 统一错误提示
    showError(msg) {
      this.error = true;
      this.errorMsg = msg;
      uni.showToast({
        title: msg,
        icon: "none",
        duration: 1500
      });
    }
  }
};
</script>

<style scoped>
/* 基础样式 - 修复uni-app兼容性问题 */
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
  box-sizing: border-box;
}

.login-form {
  background-color: #ffffff;
  border-radius: 12px;
  padding: 24px;
  width: 100%;
  max-width: 360px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.logo-container {
  text-align: center;
  margin-bottom: 24px;
}

.login-logo {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin: 0 auto;
}

.input-group {
  margin-bottom: 16px;
}

.label {
  display: block;
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.input-field {
  width: 100%;
  padding: 12px;
  border: 1px solid #ccc;
  border-radius: 8px;
  box-sizing: border-box;
}

.input-field input {
  width: 100%;
  height: 100%;
}

.login-button {
  width: 100%;
  padding: 10px;
  background-color: #007bff;
  color: #ffffff;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  margin-bottom: 16px;
}

.login-button[disabled] {
  background-color: #e0e0e0;
  opacity: 0.6;
}

.register-link {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #007bff;
}

.link-text {
  text-decoration: none;
  cursor: pointer;
}

/* 状态样式 */
.loading-tip {
  text-align: center;
  color: #666;
  font-size: 14px;
  margin: 12px 0;
}

.error-tip {
  text-align: center;
  color: #ff4d4f;
  font-size: 14px;
  margin-top: 8px;
}

.input-error {
  border: 1px solid #ff4d4f;
}
</style>